package concurrent.mysynchronized;

/**
 * @package concurrent.mysynchronized
 * @Class SynchronizedDemo
 * @Description TODO
 * @Author zhangxinhua
 * @Date 20-1-13 下午5:07
 */
public class SynchronizedDemo {
    /**
     * 共享变量
     */
    private boolean ready = false;
    private int result = 0;
    private int number = 1;

    /**
     * 读操作
     */
    public void read() {
        if (ready) {
            result = number*3;
        }
        System.out.println("result的值：" + result);
    }

    /**
     * 写操作
     */
    public void write() {
        ready=true;
        number = 2;
    }
    private class ReadWriteThread extends Thread{

        private boolean flag;

        public ReadWriteThread(boolean flag) {
            this.flag = flag;
        }

        @Override
        public void run() {
            if (flag) {
                write();
            } else {
                read();
            }
        }
    }

    public void test() {
        this.new ReadWriteThread(true).start();
        this.new ReadWriteThread(false).start();
    }
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            SynchronizedDemo demo = new SynchronizedDemo();
            demo.test();
        }
    }
}
